package com.delaphone.flocash.web.action;

import com.delaphone.flocash.model.FUser;
import com.delaphone.flocash.web.service.MailService;
import com.delaphone.flocash.service.UserService;
import com.delaphone.flocash.util.SecurityUtil;
import com.delaphone.flocash.web.util.Validate;
import com.opensymphony.xwork2.Action;
import java.util.Random;

/**
 *
 * @author tamdx
 */
public class LostPassAction extends BaseAction {

    private MailService mailService;
    private UserService userService;
    private String email;

    public String index() {
        return Action.SUCCESS;
    }

    public String getPass() {
        validateFields();
        FUser u = userService.getUserByEmail(email);
        if (u != null) {
            Random r = new Random();
            String rPass = Long.toString(Math.abs(r.nextLong()), 36).substring(0, 7);
            u.setPassword(SecurityUtil.makePwd(rPass));//Re-setup password
            userService.saveChange(u);
            mailService.sendMail(email, "Reset Pass", "Hello " + email + "\n\nYour new Password is:" + rPass);
            request.setAttribute("msg", getText("lostpass.send.success"));
        } else if (getActionErrors().isEmpty()) {
            request.setAttribute("msg", getText("lostpass.email.notexit"));
        }
        return Action.INPUT;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public MailService getMailService() {
        return mailService;
    }

    public void setMailService(MailService mailService) {
        this.mailService = mailService;
    }

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public void validateFields() {
        if (Validate.isEmptyString(email)) {
            addActionError(getText("lostpass.warn"));
        } else if (!Validate.isEmail(email)) {
            addActionError(getText("lostpass.format"));
        }
    }
}
